package com.bstek.urule.console.servlet.constant;

import com.bstek.urule.RuleException;
import com.bstek.urule.console.EnvironmentUtils;
import com.bstek.urule.console.FreemarkerUtils;
import com.bstek.urule.console.User;
import com.bstek.urule.console.repository.RepositoryService;
import com.bstek.urule.console.servlet.RequestContext;
import com.bstek.urule.console.servlet.base.BaseController;
import com.bstek.urule.model.library.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author zhouchaoliang
 * @since 2021/12/9
 */
@Controller
public class ConstantController extends BaseController {
    @Autowired
    private RepositoryService repositoryService;

    @GetMapping("/urule/constanteditor")
    public ModelAndView constant(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView("/constant-editor");
        mv.addObject("contextPath", req.getContextPath());
        return mv;
    }

    @ResponseBody
    @PostMapping(value = "/urule/constant/saveFile")
    public void saveFile(@RequestBody ConstantSaveDto constantSaveDto, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file = constantSaveDto.getFile();
        List<Constant> data = constantSaveDto.getData();
        String versionComment = constantSaveDto.getVersionComment();
        Boolean newVersion = constantSaveDto.getNewVersion();
        User user = EnvironmentUtils.getLoginUser(new RequestContext(req, resp));
        String content1 = constantSaveDto.getContent();
        String encode = URLDecoder.decode(content1, "UTF-8");
        System.out.println(encode);
        try {
            String content = new FreemarkerUtils("constant.xml").data("data", data).build();
            System.out.println(content);
//            repositoryService.saveFile(file, content, newVersion, versionComment, user);
        } catch (Exception ex) {
            throw new RuleException(ex);
        }
    }

}
